package com.saicmotor.viewmodeldemo;

import androidx.lifecycle.ViewModel;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author wangty07011.
 * @date 20-8-31
 */
public class TimerViewModel extends ViewModel {

    private Timer mTimer;
    private int currentSecond;

    /**
     * 开始计时
     */
    public void startTiming() {
        if (mTimer == null) {
            currentSecond = 0;
            mTimer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    currentSecond++;
                    if (mOnTimeChangeListener != null) {
                        mOnTimeChangeListener.onTimeChanged(currentSecond);
                    }
                }
            };
            mTimer.schedule(task, 1000, 1000);
        }
    }

    /**
     * 通过接口的方式，通知调用者
     */
    public interface OnTimeChangeListener {
        void onTimeChanged(int second);
    }

    private OnTimeChangeListener mOnTimeChangeListener;

    public void setOnTimeChangeListener(OnTimeChangeListener onTimeChangeListener) {
        this.mOnTimeChangeListener = onTimeChangeListener;
    }

    /**
     * 清理资源
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        mTimer.cancel();
    }
}
